package com.spring.statemachine.controller;

import com.spring.statemachine.Events;
import com.spring.statemachine.States;
import org.springframework.statemachine.StateContext;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.action.Action;
import org.springframework.statemachine.config.StateMachineBuilder;
import org.springframework.statemachine.config.StateMachineBuilder.Builder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;

/**
 * @author mayixiang
 * @date 2021-02-05 10:41
 */
@RestController
@RequestMapping("web")
public class WebController {

    public Map<String, StateMachine> stateMachineList = new HashMap<>();

    @GetMapping("create")
    public String create() throws Exception {
        Builder<States, Events> builder = StateMachineBuilder.builder();
        builder.configureStates()
            .withStates()
                .initial(States.STATE1)
                .states(EnumSet.allOf(States.class));
        builder.configureTransitions()
            .withExternal()
                .source(States.STATE1).target(States.STATE2)
                .event(Events.EVENT1)
                .and()
            .withExternal()
                .source(States.STATE2).target(States.STATE1)
                .action(getAction())
                .event(Events.EVENT2);
        StateMachine<States, Events> build = builder.build();
        stateMachineList.put(build.getId(), build);
        return build.getId();
    }

    private Action<States, Events> getAction(){
        return new Action<States, Events>() {
            @Override public void execute(StateContext<States, Events> context) {
            }
        };
    }

    @GetMapping("event")
    public void event(@RequestParam("id") String id, @RequestParam("event") Events event){
        StateMachine stateMachine = stateMachineList.get(id);
        stateMachine.sendEvent(event);
    }

}
